#include "Primitive.h"
#include "DX.h"

Primitive::Primitive( ) : Object3D(), _vertexBuffer( 0 ), _sizeBuffer( 0 )
{

}

void Primitive::setBuffer( std::vector< LCVertexPosDiffuse >& vertices )
{	
	if ( _vertexBuffer ) _vertexBuffer->Release();

	HRESULT hr = DX::_()->device->CreateVertexBuffer( sizeof( LCVertexPosDiffuse ) * vertices.size(), D3DUSAGE_WRITEONLY, LCVertexPosDiffuse::FORMAT, D3DPOOL_DEFAULT, &_vertexBuffer, 0 );
	if ( hr ) throw std::wstring( TEXT( "Primitive: VertexBuffer not created!!!" ) );

	void* bufferMemory;
	hr = _vertexBuffer->Lock( 0, sizeof( LCVertexPosDiffuse ) * vertices.size(), &bufferMemory, NULL );
	memcpy( bufferMemory, &vertices[ 0 ], sizeof( LCVertexPosDiffuse ) * vertices.size() );
	_vertexBuffer->Unlock();

	_sizeBuffer = vertices.size();
}

void Primitive::setBuffer( std::vector< LCVertexTexture >& vertices )
{	
	if ( _vertexBuffer ) _vertexBuffer->Release();

	HRESULT hr = DX::_()->device->CreateVertexBuffer( sizeof( LCVertexTexture ) * vertices.size(), D3DUSAGE_WRITEONLY, LCVertexTexture::FORMAT, D3DPOOL_DEFAULT, &_vertexBuffer, 0 );
	if ( hr ) throw std::wstring( TEXT( "Primitive: VertexBuffer not created!!!" ) );

	void* bufferMemory;
	hr = _vertexBuffer->Lock( 0, sizeof( LCVertexTexture ) * vertices.size(), &bufferMemory, NULL );
	memcpy( bufferMemory, &vertices[ 0 ], sizeof( LCVertexTexture ) * vertices.size() );
	_vertexBuffer->Unlock();

	_sizeBuffer = vertices.size();
}

IDirect3DVertexBuffer9*	Primitive::buffer()
{
	return _vertexBuffer;
}

Primitive::~Primitive()
{
	if ( _vertexBuffer ) _vertexBuffer->Release();
}

size_t Primitive::sizeBuffer()
{
	return _sizeBuffer;
}

void Primitive::setColor( D3DCOLOR color )
{
	void* bufferMemory;
	_vertexBuffer->Lock( 0, sizeof( LCVertexPosDiffuse ) * _sizeBuffer, &bufferMemory, NULL );
	
	LCVertexPosDiffuse* buffer = ( LCVertexPosDiffuse* )bufferMemory;

	for ( size_t i = 0; i < _sizeBuffer; ++i )
	{
		buffer[ i ].color = color;
	}
	
	_vertexBuffer->Unlock();
}